package ui;

import java.util.List;

import application.ApplicationModel;

import com.vaadin.annotations.Theme;
import com.vaadin.event.LayoutEvents.LayoutClickEvent;
import com.vaadin.event.LayoutEvents.LayoutClickListener;
import com.vaadin.shared.ui.MarginInfo;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.ui.Component;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Layout;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.Runo;

import data.Celebrity;


@SuppressWarnings("serial")
@Theme("demoopenis")
public abstract class ResultsView extends VerticalLayout {
	
	private String query;
	private ApplicationModel application;
	
	private List<Celebrity> celebrities;

	
	public ResultsView(ApplicationModel application, String query) {
		this.application = application;
		this.query = query;
		
		// <loading>
		celebrities = application.findCelebrities(query);
		// </loading>
		
		setMargin(new MarginInfo(false, true, false, true));
		setSpacing(true);
		initLabelLayout();
		initResultsLayout();
	}
	
	
	private void initLabelLayout() {
		String text = "<h2>" + celebrities.size() + " results found for <i>" + query + "</i>:</h2>"
				+ "<hr>";
		
		addComponent(new Label(text, ContentMode.HTML));
	}
	
	private void initResultsLayout() {
		VerticalLayout layout = new VerticalLayout();	
		layout.setSpacing(true);
		addComponent(layout);
		
		layout.setSizeFull();
		setExpandRatio(layout, 1);
		
		for(Celebrity celebrity : celebrities)
			layout.addComponent(getCelebrityResult(celebrity));
	}
	
	@SuppressWarnings("deprecation")
	private Component getCelebrityResult(final Celebrity celebrity) {
		Label label = new Label(getCelebrityTitle(celebrity), ContentMode.HTML);
		
		CssLayout layout = new CssLayout();
        layout.addStyleName(Runo.CSSLAYOUT_SELECTABLE);
        layout.addStyleName(Runo.CSSLAYOUT_SELECTABLE_SELECTED);
        layout.addListener(
        		new LayoutClickListener() {
        			@Override
        			public void layoutClick(LayoutClickEvent event) {
        				
        				setMainLayout(new CelebrityClothesView(application, celebrity));
        				
        			}
        		}
        		);
        
        
        VerticalLayout align = new VerticalLayout();
        align.addComponent(label);
        layout.addComponent(align);
		
		return layout;
	}
	

	private String getCelebrityTitle(Celebrity celebrity) {
		return "<b>" + celebrity.getStageName() + "</b>&nbsp;&nbsp;(<i>" 
				+ celebrity.getFirstName() + " " 
				+ celebrity.getFamilyName() + "</i>)";
	}
	
	
	protected abstract void setMainLayout(Layout layout);

}
